package com.kingsoft.demo.xml.dom4j;

import java.io.FileWriter;
import java.io.Writer;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * 创建xml文档
 *
 */
public class XmlCreator {
	
	public void createXml() throws Exception{
		
		//创建一个空的文档对象
		Document doc=DocumentHelper.createDocument();
		
		//添加元素节点
		Element el_rowdata=doc.addElement("ROWDATA");
		Element el_row=el_rowdata.addElement("ROW");
		Element el_empno=el_row.addElement("EMPNO");
		Element el_ename=el_row.addElement("ENAME");
		
		//设置节点
		el_empno.setText("7500");
		el_ename.setText("史密斯");
		el_ename.setAttributeValue("firstname", "Tom");

		
		//输出流
		Writer w= new FileWriter("src/demo.xml");
		
		OutputFormat opf=OutputFormat.createPrettyPrint();//设置输出格式
		opf.setEncoding("GBK");   //设置字符集
		
		XMLWriter xw=new XMLWriter(w,opf);		
		xw.write(doc);	
		xw.close();

	}
	
	public static void main(String[] args) {
		
		XmlCreator xc=new XmlCreator();
		try {
			xc.createXml();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
